﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using NoteHelper.IBusiness;
using NoteHelper.Model;
using NoteHelper.Utils;
using Unity;

namespace NoteHelper.Account
{
    public partial class Acct001 : WeifenLuo.WinFormsUI.Docking.DockContent,IBaseView
	{
		private log4net.ILog logger;
        private DevAge.ComponentModel.IBoundList bd;
        private const string Pre = "Acct_";

        public Acct001()
		{
			InitializeComponent();
        }

		private void Acct001_Load(object sender, EventArgs e)
        {
            var table = new DataTable();
            table.Columns.Add("id", typeof(bool));
            table.Columns.Add("text", typeof(string));
            table.Rows.Add(new object[] { DBNull.Value, "全部" });
            table.Rows.Add(new object[] { true, "作废" });
            table.Rows.Add(new object[] { false, "正常" });
            Acct_Discarded.DataSource = table;
            Acct_Discarded.DisplayMember = "text";
            Acct_Discarded.ValueMember = "id";

            logger = log4net.LogManager.GetLogger("NoteHelper.Account.Acct001");
			displayGrid.FixedRows = 1;
			displayGrid.FixedColumns = 1;
            CreateColumns();

            Type entityType = typeof(Model.Account);
            label1.Text = entityType.GetDisplayName("Id");
            label2.Text = entityType.GetDisplayName("CreateDate");
            label3.Text = entityType.GetDisplayName("Name");
            label4.Text = entityType.GetDisplayName("Description");

            var container = UnityHelper.GetContainer();
            var accountManager = container.Resolve<IAccountManager>();
            var controller = new Acct001Controller(this, accountManager);
		}

        private void CreateColumns()
        {
            // 创建显示的样式
            SourceGrid.Cells.Views.Cell viewDiscarded = new SourceGrid.Cells.Views.Cell();
            viewDiscarded.Font = new Font(displayGrid.Font, FontStyle.Bold);
            viewDiscarded.ForeColor = Color.DarkGreen;

            // 创建条件判断
            SourceGrid.Conditions.ConditionView selectedConditionBold = new SourceGrid.Conditions.ConditionView(viewDiscarded);
            selectedConditionBold.EvaluateFunction = delegate (SourceGrid.DataGridColumn column, int gridRow, object itemRow)
            {
                DataRowView row = (DataRowView)itemRow;
                return row["Discarded"] is bool && (bool)row["Discarded"] == false;
            };

            SourceGrid.DataGridColumn gridColumn;

            gridColumn = displayGrid.Columns.Add("$_rowIndex", "下标", typeof(int));
            gridColumn.Conditions.Add(selectedConditionBold);
            gridColumn.Width = 50;

            gridColumn = displayGrid.Columns.Add("Id", "银行编号", typeof(string));
            gridColumn.Conditions.Add(selectedConditionBold);
            gridColumn.Width = 100;

            string dtFormat2 = "yyyy-MM-dd";
            string[] dtParseFormats = new string[] { dtFormat2 };
            System.Globalization.DateTimeStyles dtStyles = System.Globalization.DateTimeStyles.AllowInnerWhite | System.Globalization.DateTimeStyles.AllowLeadingWhite | System.Globalization.DateTimeStyles.AllowTrailingWhite | System.Globalization.DateTimeStyles.AllowWhiteSpaces;
            TypeConverter dtConverter = new DevAge.ComponentModel.Converter.DateTimeTypeConverter(dtFormat2, dtParseFormats, dtStyles);
            SourceGrid.Cells.Editors.TextBoxUITypeEditor editorDt2 = new SourceGrid.Cells.Editors.TextBoxUITypeEditor(typeof(DateTime));
            editorDt2.TypeConverter = dtConverter;
            gridColumn = displayGrid.Columns.Add("CreateDate", "开户日期", editorDt2);
            gridColumn.Conditions.Add(selectedConditionBold);
            gridColumn.Width = 100;

            gridColumn = displayGrid.Columns.Add("Name", "账号名称", typeof(string));
            gridColumn.Conditions.Add(selectedConditionBold);
            gridColumn.Width = 120;

            gridColumn = displayGrid.Columns.Add("Description", "备注", typeof(string));
            gridColumn.Conditions.Add(selectedConditionBold);
            gridColumn.Width = 300;

            #region ==== 格式化显示 ====
            SourceGrid.Cells.Editors.ComboBox externalIdEditor = new SourceGrid.Cells.Editors.ComboBox(typeof(bool));
            externalIdEditor.StandardValues = new bool[] { true, false };
            externalIdEditor.StandardValuesExclusive = true;
            externalIdEditor.Control.FormattingEnabled = true;

            DevAge.ComponentModel.Validator.ValueMapping mapping = new DevAge.ComponentModel.Validator.ValueMapping();
            mapping.ValueList = new bool[] { true, false };
            mapping.DisplayStringList = new string[] { "作废", "正常" };
            mapping.BindValidator(externalIdEditor);

            gridColumn = displayGrid.Columns.Add("Discarded", "是否作废", externalIdEditor);
            gridColumn.Conditions.Add(selectedConditionBold);
            gridColumn.Width = 60;
            #endregion

            gridColumn = displayGrid.Columns.Add("DiscardedDate", "作废日期", typeof(DateTime));
            gridColumn.Conditions.Add(selectedConditionBold);
            gridColumn.Width = 100;

            foreach (SourceGrid.DataGridColumn col in displayGrid.Columns)
            {
                col.DataCell.AddController(SourceGrid.Cells.Controllers.ToolTipText.Default);
                col.DataCell.Model.AddModel(MyToolTipModel.Default);
            }
        }

        private class MyToolTipModel : SourceGrid.Cells.Models.IToolTipText
        {
            public static readonly MyToolTipModel Default = new MyToolTipModel();

            public string GetToolTipText(SourceGrid.CellContext cellContext)
            {
                SourceGrid.DataGrid grid = (SourceGrid.DataGrid)cellContext.Grid;
                DataRowView row = (DataRowView)grid.Rows.IndexToDataSourceRow(cellContext.Position.Row);
                if (row != null)
                {
                    if (bool.Equals(row["Discarded"], true))
                        return "Row " + cellContext.Position.Row.ToString() + " is Discarded";
                    else
                        return "Row " + cellContext.Position.Row.ToString() + " is NOT Discarded";
                }
                else
                    return string.Empty;
            }
        }

        #region ==== IBaseView Impl ====

        private DataTable _displayList;
		public DataTable DisplayList
		{
			get { return _displayList; }
			set
			{
				if (value == null) return;
				_displayList = value;
				
				bd = new DevAge.ComponentModel.BoundDataView(_displayList.DefaultView);
                bd.AllowNew = false;
                bd.AllowEdit = false;
                bd.AllowDelete = false;
                displayGrid.DataSource = bd;
			}
		}
		public FormCommand Cmd { get; set; }
		public Hashtable RowData
        {
            get
            {
                return splitContainer1.Panel1.GetData(Pre);
            }
            set
            {
                splitContainer1.Panel1.SetData(Pre, value);
            }
        }
		public event EventHandler Insert;
		public event EventHandler Edit;
		public event EventHandler Remove;
		public event EventHandler Copy;
		public event EventHandler Query;
		public event EventHandler Accept;
		public event EventHandler Cancel;
		public event EventHandler Print;
		public event EventHandler Help;
		public void BeginEdit()
        {
            Acct_Id.Enabled = true;
            Acct_Name.Enabled = true;
            Acct_Description.Enabled = true;
            Acct_CreateDate.Enabled = true;
            Acct_Discarded.Enabled = Cmd == FormCommand.Query;
        }
		public void EndEdit()
        {
            Acct_Id.Enabled = false;
            Acct_Name.Enabled = false;
            Acct_Description.Enabled = false;
            Acct_CreateDate.Enabled = false;
            Acct_Discarded.Enabled = false;
        }
		public int GetRowIndex()
		{
			int rowIndex = -1;
			object[] rows = displayGrid.SelectedDataRows;
			if (rows != null && rows.Length > 0)
			{
				DataRowView row = (DataRowView)rows[0];
				int.TryParse(row["$_rowIndex"].ToString(), out rowIndex);
			}
			return rowIndex;
        }

        public void Notify(string notification)
        {
            AlterMsg.Info(notification);
        }

        #endregion

        #region ==== Toolbar Event ====
        /// <summary>
        /// 添加
        /// </summary>
        private void InsertButtonClick(object sender, EventArgs e)
		{
			Insert?.Invoke(sender, e);
		}
		/// <summary>
		/// 修改
		/// </summary>
		private void EditButtonClick(object sender, EventArgs e)
		{
			Edit?.Invoke(sender, e);
		}
		/// <summary>
		/// 删除
		/// </summary>
		private void RemoveButtonClick(object sender, EventArgs e)
		{
			Remove?.Invoke(sender, e);
		}
		/// <summary>
		/// 复制
		/// </summary>
		private void CopyButtonClick(object sender, EventArgs e)
		{
			Copy?.Invoke(sender, e);
		}
		/// <summary>
		/// 查询
		/// </summary>
		private void QueryButtonClick(object sender, EventArgs e)
		{
			Query?.Invoke(sender, e);
		}
		/// <summary>
		/// 确定
		/// </summary>
		private void AcceptButtonClick(object sender, EventArgs e)
		{
			Accept?.Invoke(sender, e);
		}
		/// <summary>
		/// 取消
		/// </summary>
		private void CancelButtonClick(object sender, EventArgs e)
		{
			Cancel?.Invoke(sender, e);
		}
		/// <summary>
		/// 打印
		/// </summary>
		private void PrintButtonClick(object sender, EventArgs e)
		{
			Print?.Invoke(sender, e);
		}
		/// <summary>
		/// 帮助
		/// </summary>
		private void HelpButtonClick(object sender, EventArgs e)
		{
			Help?.Invoke(sender, e);
		}
		#endregion
	}
}
